package org.vectrics.mail.struts;

import java.util.Date;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Level;
import org.vectrics.common.http.HttpUtils;
import org.vectrics.common.util.StringUtils;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.mail.FileEmailTemplate;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;

public class SendBulkEmailAction extends VectricsStrutsAction {
	public static final String TEMPLATE_FILE_NAME = "template.dat";
	
	public SendBulkEmailAction() {
		super();
	}

	@Override
	protected String doExecute(VectricsActionData actionData)
			throws JspException {
		Request request = actionData.getRequest();
		HttpUtils.logRequestInfo(request, log, Level.INFO);		
		String forward = "success";
		log.info("Checking which button was pressed");
		if (actionData.wasButtonPressed("back")) {
			forward = "back";
			BulkEmailForm form = (BulkEmailForm)actionData.getForm();
			if (form == null) {
				log.info("Form is null, creating form and attaching to request");
				form = new BulkEmailForm();
				form.setCategoryId(actionData.getRequest().getParameter("categoryId"));
				form.setTemplateId(actionData.getRequest().getParameter("templateId"));
				form.setSubject(actionData.getRequest().getParameter("subject"));
				form.setFromName(actionData.getRequest().getParameter("fromName"));
				form.setFromEmail(actionData.getRequest().getParameter("fromEmail"));
				if (StringUtils.isNullOrBlank(form.getTemplateId()) == false) { 
					log.info("Finding template for id = " + form.getTemplateId());
					FileEmailTemplate template = CoreServiceLocator
							.getSystemService().findFileEmailTemplateWithId(new Long(form.getTemplateId()));
					form.setTemplateText(template.getText());
				}
				actionData.setForm(form);
				log.info("form = " + form);
			} else {
				log.info("form already executed");
			}
			log.info("Returning back to email edit form" +
					"\r\n  categoryId = " + form.getCategoryId() +
					"\r\n  templateId = " + form.getTemplateId()
					);
			
		} else if (actionData.wasButtonPressed("cancel")) {
			forward = "cancel";
		} else {
			forward = "success"; 
			log.info("Sending email to recipients");
			String stageTime = actionData.getRequest().getParameter("stageDateMillis");
			Long stageLong = new Long(stageTime);
			Date stageDate = new Date(stageLong.longValue());
			//String senderParam = actionData.getRequest().getParameter("senderId");
			Person sender = ThreadProperties.getPerson();
			LetterStagingManager stagingManager = new LetterStagingManager(sender, stageDate);
			stagingManager.sendAll(sender);
		}
		return forward;
	}

}

